How to convert string into int
in C#?
How to convert string into int in C#?
663
11-Jun-2024
Ashutosh Kumar Verma
12-Jun-2024Convert string to int in C#
Converting a string to an integer in C# can be done in many ways depending on the specific needs of your application. Here are general ways to do this.
Using int.Parse
The int.Parse method is used to convert a string to an integer. Throw a FormatException if the string is not a valid integer.
Syntax-
using int.TryParse
The int.TryParse method attempts to convert a string to an integer and returns a boolean indicating whether the conversion was successful or not. This method is safe because it does not throw an exception if the conversion fails.
Syntax-
Using Convert.ToInt32
The Convert.ToInt32 method converts the specified string position of any number to a 32-bit equivalent signed integer. It handles null values by returning 0 and throws a FormatException if the string is not a valid integer.
Syntax-
Handling exceptions and edge cases
When using int.Parse or Convert.ToInt32, you must deal with potential exceptions to avoid runtime errors.
Syntax-
int.tryParsebecause it returns the boolean value true or false.Example-
The below example illustrate the different way to convert string into int in C#
Output-
Also, Read: What is Boxing and Unboxing in C#?